import notification from 'ant-design-vue/es/notification'
import axios from 'axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import storage from 'store'
// import { BASE_URL } from '@/consts'

// 导出
export function handleExport (params, url, success, fail) {
  axios({
    method: 'post',
    responseType: 'blob', // 因为是流文件，所以要指定blob类型
    // url: BASE_URL + url,
    url: process.env.VUE_APP_API_BASE_URL + url,
    data: params,
    headers: {
      Authorization: storage.get(ACCESS_TOKEN)
    }
  }).then(({ data, headers }) => {
    const { type } = data || {}
    if (type === 'application/octet-stream' || type === 'application/pdf') {
      let fileName = headers['content-disposition'].split(';')[1].split('filename=')[1]
      fileName = decodeURI(escape(fileName))
      fileName = fileName.replace(/"/g, '')
      const href = URL.createObjectURL(data)
      Object.assign(document.createElement('a'), {
        href,
        download: fileName
      }).click()
      URL.revokeObjectURL(href)
      if (success) success()
    } else {
      const reader = new FileReader()
      reader.readAsText(data, 'utf-8')
      reader.onload = () => {
        const obj = JSON.parse(reader.result)
        notification.error({
          message: '提示',
          description: obj.msg,
          duration: 4
        })
      }
      if (fail) fail()
    }
  })
}
